//
//  FringdlyLinkViewController.m
//  YinHang
//
//  Created by idea on 14-9-17.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "FringdlyLinkViewController.h"
#import "AddFriendlyLinkViewController.h"

#import "FriendlyLink.h"
#import "GetLink.h"
#import "FriendlyLinkCell.h"

@interface FringdlyLinkViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,ASIHTTPRequestDelegate,LinkListServiceDelegate>{
    
    NSMutableArray *linkarr;
    NSInteger btnTag;//修改删除链接用
    
    ASIFormDataRequest *editRequest_;//编辑请求
    ASIFormDataRequest *delRequest_;//删除请求
    
    GetLink *linkService;
}

@end

@implementation FringdlyLinkViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //self.navigationController.navigationBarHidden = NO;
    self.navigationItem.title = @"友情链接";
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    
    //添加
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    addBtn.frame = CGRectMake(0, 0, 60, 35);
    UIImage *postBtn_bgImg = [UIImage imageNamed:@"postbtn_bg"];
    [addBtn setTitle:@"添加" forState:UIControlStateNormal];
    [addBtn setTintColor:[UIColor whiteColor]];
    [addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [addBtn setBackgroundImage:[postBtn_bgImg stretchableImageWithLeftCapWidth:postBtn_bgImg.size.width*0.5f topCapHeight:postBtn_bgImg.size.height*0.5f] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *addBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:addBtn];
    
    if (ios7) {
        self.navigationItem.rightBarButtonItems = @[negativeSpacer,addBarButtonItem];
    }else{
        self.navigationItem.rightBarButtonItems = @[addBarButtonItem];
    }
    
    linkarr = [NSMutableArray array];
    
    // 屏幕适配
    _friendlyLinkTableView.frame = CGRectMake(_friendlyLinkTableView.frame.origin.x, 64, _friendlyLinkTableView.bounds.size.width,IPHONE5 ? 504: 416);
    _friendlyLinkTableView.rowHeight = 84;
    [self setUI];
    
    
    //[self.view bringSubviewToFront:_friendlyLinkTableView];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    

    //刷新
    [self getDate];
    [self setupRefresh];
    [_friendlyLinkTableView headerBeginRefreshing];
}
#pragma mark - Custom Method
//获取数据
-(void)getDate{
    linkService = [[GetLink alloc]init];
    linkarr = linkService.pageInfo.dataArr;
    linkService.delegate = self;
}
//进入添加友情链接页面
-(void)add{
    AddFriendlyLinkViewController *aflvc = [[AddFriendlyLinkViewController alloc]initWithNibName:@"AddFriendlyLinkViewController" bundle:nil];
    
    aflvc.navTitle = @"添加链接";
    [self.navigationController pushViewController:aflvc animated:YES];
      //  NSLog(@"add");
}

-(void)setUI{
    
    _friendlyLinkTableView.dataSource = self;
    _friendlyLinkTableView.delegate = self;
    
    
}

-(void)back{
    //self.navigationController.navigationBarHidden = YES;
    [self.navigationController popViewControllerAnimated:YES];
}
//修改链接
-(void)alterCell:(id)sender{
    
    UIButton *btn = sender;
    NSLog(@"%i",btn.tag);
    NSInteger row = btn.tag - 10;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:linkarr.count];
    AddFriendlyLinkViewController *aflvc = [[AddFriendlyLinkViewController alloc]initWithNibName:@"AddFriendlyLinkViewController" bundle:nil];
    aflvc.linkId = linkService.pageInfo.dataArr[row][@"kid"];
    aflvc.webName_ = linkService.pageInfo.dataArr[row][@"kname"];
    aflvc.webURL_ = linkService.pageInfo.dataArr[row][@"kweb"];
    aflvc.navTitle = @"修改链接";
    [_friendlyLinkTableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.navigationController pushViewController:aflvc animated:YES];
}
//删除链接
-(void)deleteCell:(id)sender{
    
    UIButton *btn = sender;
    NSLog(@"%i",btn.tag);
    btnTag = btn.tag - 10;
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"是否删除此条信息？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    
    

    
}
#pragma mark - UITableViewControllerDelegate

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"LinkCell";
    
    
    FriendlyLinkCell *cell = (FriendlyLinkCell *)[tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = (FriendlyLinkCell *)[[NSBundle mainBundle]loadNibNamed:@"FriendlyLinkCell" owner:Nil options:Nil][0];
        //添加图片
        UIImageView *img_view = (UIImageView *)[cell.contentView viewWithTag:1];
        img_view.image = [UIImage imageNamed:@"item_64"];
    }
    
    NSUInteger row = [indexPath row];
    
    [cell.AlterBtn addTarget:self action:@selector(alterCell:) forControlEvents:UIControlEventTouchUpInside];//修改网址
    cell.AlterBtn.tag = row + 10;
    [cell.DeleteBtn addTarget:self action:@selector(deleteCell:) forControlEvents:UIControlEventTouchUpInside];//删除链接
    cell.DeleteBtn.tag = row + 10;
    
    if (linkService.pageInfo.dataArr.count != 0) {
    
    UILabel *lblName = (UILabel *) [cell.contentView viewWithTag:2];
    UILabel *lblAdress = (UILabel *) [cell.contentView viewWithTag:3];
    lblName.text = linkService.pageInfo.dataArr[row][@"kname"];
    lblAdress.text = linkService.pageInfo.dataArr[row][@"kweb"];
        
    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (linkService.pageInfo.dataArr.count != 0) {
        return linkService.pageInfo.dataArr.count;
    }
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSUInteger row = indexPath.row;
    
    AddFriendlyLinkViewController *aflvc = [[AddFriendlyLinkViewController alloc]initWithNibName:@"AddFriendlyLinkViewController" bundle:nil];
    aflvc.navTitle = @"修改链接";
    aflvc.linkId = linkService.pageInfo.dataArr[row][@"kid"];
    aflvc.webName_ = linkService.pageInfo.dataArr[row][@"kname"];
    aflvc.webURL_ = linkService.pageInfo.dataArr[row][@"kweb"];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.navigationController pushViewController:aflvc animated:YES];
}

/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_friendlyLinkTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    /* 自动刷新(一进入程序就下拉刷新) */
    //[_tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_friendlyLinkTableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 刷新表格
    if (linkService.isQuery ||![Constants isExistenceNetwork]) {
        [_friendlyLinkTableView reloadData];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_friendlyLinkTableView headerEndRefreshing];
        return;
    }
    
    // 下拉刷新 （请求第一页数据）
    
    // 每次必须重置下 否则会数据混乱
    linkService.pageInfo.pageno = @"1";
    [linkService pageQuery];
}

- (void)footerRereshing
{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
        // 刷新表格
        [_friendlyLinkTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_friendlyLinkTableView footerEndRefreshing];
        
        return;
    }
    
    // 如果正在查询 或 没有更多数据了
//    NSLog(@"%i",linkService.isQuery);
//    NSLog(@"%i",linkService.pageInfo.hasMoreData);
    if (linkService.isQuery || !linkService.pageInfo.hasMoreData) {
        // 2. 1秒后刷新表格UI
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [_friendlyLinkTableView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [_friendlyLinkTableView footerEndRefreshing];
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText = @"没有更多数据了";
            [hud hide:YES afterDelay:1];
        });
        
        linkService.pageInfo.hasMoreData = YES;
        
        return;
    }
    
    // 如果还有更多数据 请求下一页
    [linkService.pageInfo nextPage];
    [linkService pageQuery];
}




#pragma mark - UIAlertViewDelegate
//删除处理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
       // [linkarr removeObjectAtIndex:btnTag];
        /* 请求服务器删除对应类别下的信息 */
        
        // 检查网络
        if (![Constants isExistenceNetwork]) {
            
        } else {
            delRequest_ = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:API_STR]];
            delRequest_.requestMethod = @"POST";
            // 设置超时时间
            delRequest_.timeOutSeconds = 30;
            delRequest_.delegate = self;
            // 设置参数
            NSString *action = @"linksdel";
            NSDictionary *paramsDict =  @{@"kid":linkService.pageInfo.dataArr[btnTag][@"kid"], @"uid": UNAME};
            NSString *paramsStr = [NSString JSONString:paramsDict];
            NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
            
            NSData *paramsData = [result toGBKEncodingData];
            delRequest_.postBody = [paramsData mutableCopy];
            
            [delRequest_ startAsynchronous];
        }

        [_friendlyLinkTableView reloadData];
    }
}

#pragma mark - AddOrAlterDelegate Method
//增加link
-(void)addLinkWithName:(NSString *)webName WebURL:(NSString *)webURL{
    
    
    [_friendlyLinkTableView reloadData];
}
//修改link
-(void)alterLinkAtRow:(NSInteger)row withWebName:(NSString *)webName WebURL:(NSString *)webURL{
    
    
    
    [_friendlyLinkTableView reloadData];
    
}

#pragma mark - QuestionService Delegate

- (void)didRecieveData{
    [_friendlyLinkTableView headerEndRefreshing];
    [_friendlyLinkTableView footerEndRefreshing];
    [_friendlyLinkTableView reloadData];
}
- (void)didRecieveMsg{
    [_friendlyLinkTableView headerEndRefreshing];
    [_friendlyLinkTableView footerEndRefreshing];
    [_friendlyLinkTableView reloadData];
}
#pragma mark - ASIHTTPRequestDelegate Method

- (void)requestFinished:(ASIHTTPRequest *)request {
    //NSLog(@"%@",request.responseString);
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        if (errorCode == 0) {
            //获取选中删除行索引值并通过获取的索引值删除数组中的值
            [linkService.pageInfo.dataArr removeObjectAtIndex:btnTag];
            //删除单元格的某一行时，在用动画效果实现删除过程
            [_friendlyLinkTableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:btnTag inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            [_friendlyLinkTableView reloadData];
            
            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
            
        } else {
            [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
        }
    } else {
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}
-(void)dealloc{
    linkService = nil;
    [editRequest_ cancel];
    [delRequest_ cancel];
}

@end
